package com.enjoy.concurrent.ch3;

import sun.misc.Unsafe;

public class CASTest {
    public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException, ClassNotFoundException {
        Entity entity = new Entity();

        Unsafe unsafe = UnsafeFactory.getUnsafe();
        long xOffset = UnsafeFactory.getFieldOffset(unsafe, entity.getClass(), "x");
        long yOffset = UnsafeFactory.getFieldOffset(unsafe, entity.getClass(), "y");
        long zOffset = UnsafeFactory.getFieldOffset(unsafe, entity.getClass(), "z");

        System.out.println("xOffset = " + xOffset);
        System.out.println("yOffset = " + yOffset);
        System.out.println("zOffset = " + zOffset);

        boolean successful = unsafe.compareAndSwapInt(entity, xOffset, 0, 3);
        System.out.println("successful = " + successful);

        successful = unsafe.compareAndSwapInt(entity, xOffset, 3, 5);
        System.out.println("successful = " + successful);

        successful = unsafe.compareAndSwapInt(entity, xOffset, 3, 8);
        System.out.println("successful = " + successful);
    }

    private static class Entity {
        public int x;
        public Object y;
        public int[] z = new int[16];
    }
}
